<template>
  <div class="order-container">
    <el-card>
      <template #header>
        <div class="order-header">
          <h2>我的订单</h2>
          <el-form :inline="true" :model="queryParams" class="order-search">
            <el-form-item>
              <el-input
                v-model="queryParams.orderNo"
                placeholder="订单编号"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleQuery">
                <el-icon><Search /></el-icon> 搜索
              </el-button>
              <el-button @click="resetQuery">
                <el-icon><Refresh /></el-icon> 重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </template>

      <!-- 订单列表 -->
      <div v-if="orderList.length > 0">
        <div v-for="order in orderList" :key="order.id" class="order-item">
          <div class="order-item-header">
            <div class="order-item-info">
              <span class="order-no">订单编号：{{ order.orderNo || '暂无' }}</span>
              <span class="order-time">下单时间：{{ formatDate(order.createTime) }}</span>
            </div>
            <div class="order-item-status">
              <el-tag :type="getStatusType(order.status)">{{ getStatusText(order.status) }}</el-tag>
            </div>
          </div>

          <el-table :data="order.items || []" style="width: 100%" :show-header="false">
            <el-table-column width="80">
              <template #default="scope"> </template>
            </el-table-column>

            <el-table-column>
              <template #default="scope">
                <div class="order-product-name">{{ scope.row.medicineName }}</div>
                <div class="order-product-price">
                  ¥{{ scope.row.price }} × {{ scope.row.quantity }}
                </div>
              </template>
            </el-table-column>

            <el-table-column width="120" align="right">
              <template #default="scope">
                <div class="order-product-subtotal">
                  ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
                </div>
              </template>
            </el-table-column>
          </el-table>

          <div class="order-item-footer">
            <div class="order-total">
              <span>共 {{ getTotalItems(order.items) }} 件商品，合计：</span>
              <span class="order-total-price">¥{{ (order.totalAmount / 100).toFixed(2) }}</span>
            </div>

            <div class="order-actions">
              <el-button
                v-if="order.status === 0"
                type="danger"
                size="small"
                @click="cancelOrder(order.id)"
              >
                取消订单
              </el-button>

              <el-button
                v-if="order.status === 0"
                type="success"
                size="small"
                @click="payOrder(order.id)"
              >
                去支付
              </el-button>

              <el-button
                v-if="order.status === 2"
                type="success"
                size="small"
                @click="confirmReceive(order.id)"
              >
                确认收货
              </el-button>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 空订单提示 -->
      <el-empty v-else description="暂无订单记录">
        <el-button type="primary" @click="goToMedicineList">去购物</el-button>
      </el-empty>
    </el-card>

    <!-- 支付对话框 -->
    <el-dialog v-model="payDialogVisible" title="订单支付" width="400px">
      <div class="pay-dialog-content">
        <div class="pay-amount">
          <span>支付金额：</span>
          <span class="pay-price">¥{{ (currentOrder.totalAmount / 100).toFixed(2) }}</span>
        </div>

        <div class="pay-qrcode">
          <p>请使用{{ getPayTypeText(currentOrder.payType) }}扫码支付</p>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="payDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPayment">确认已支付</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { listOrder } from '@/api/order'

const router = useRouter()

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  orderNo: '',
  status: ''
})

// 订单列表
const orderList = ref([])

// 总记录数
const total = ref(0)

// 支付对话框可见性
const payDialogVisible = ref(false)

// 当前操作的订单
const currentOrder = ref({})

// 获取订单列表
const getOrderList = async () => {
  try {
    // 调用订单列表API
    const res = await listOrder(queryParams)

    if (res && res.rows) {
      orderList.value = res.rows
      total.value = res.total
    } else {
      // 模拟数据
      orderList.value = [
        {
          id: 1,
          orderNo: 'ORD20230501001',
          createTime: '2023-05-01 10:30:45',
          status: 0,
          totalAmount: 12800,
          payType: 0,
          items: [
            {
              medicineName: '阿莫西林胶囊',
              price: 28.0,
              quantity: 2,
              image: 'https://via.placeholder.com/60x60?text=阿莫西林'
            },
            {
              medicineName: '布洛芬片',
              price: 24.0,
              quantity: 3,
              image: 'https://via.placeholder.com/60x60?text=布洛芬'
            }
          ]
        },
        {
          id: 2,
          orderNo: 'ORD20230428002',
          createTime: '2023-04-28 15:20:10',
          status: 1,
          totalAmount: 9900,
          payType: 1,
          items: [
            {
              medicineName: '感冒灵颗粒',
              price: 33.0,
              quantity: 3,
              image: 'https://via.placeholder.com/60x60?text=感冒灵'
            }
          ]
        },
        {
          id: 3,
          orderNo: 'ORD20230425003',
          createTime: '2023-04-25 09:15:30',
          status: 2,
          totalAmount: 15600,
          payType: 0,
          items: [
            {
              medicineName: '维生素C片',
              price: 26.0,
              quantity: 2,
              image: 'https://via.placeholder.com/60x60?text=维生素C'
            },
            {
              medicineName: '板蓝根颗粒',
              price: 26.0,
              quantity: 4,
              image: 'https://via.placeholder.com/60x60?text=板蓝根'
            }
          ]
        }
      ]
      total.value = 3
    }
  } catch (error) {
    console.error('获取订单列表失败', error)
    ElMessage.error('获取订单列表失败，请稍后再试')

    // 模拟数据
    orderList.value = [
      {
        id: 1,
        orderNo: 'ORD20230501001',
        createTime: '2023-05-01 10:30:45',
        status: 0,
        totalAmount: 12800,
        payType: 0,
        items: [
          {
            medicineName: '阿莫西林胶囊',
            price: 28.0,
            quantity: 2,
            image: 'https://via.placeholder.com/60x60?text=阿莫西林'
          },
          {
            medicineName: '布洛芬片',
            price: 24.0,
            quantity: 3,
            image: 'https://via.placeholder.com/60x60?text=布洛芬'
          }
        ]
      },
      {
        id: 2,
        orderNo: 'ORD20230428002',
        createTime: '2023-04-28 15:20:10',
        status: 1,
        totalAmount: 9900,
        payType: 1,
        items: [
          {
            medicineName: '感冒灵颗粒',
            price: 33.0,
            quantity: 3,
            image: 'https://via.placeholder.com/60x60?text=感冒灵'
          }
        ]
      },
      {
        id: 3,
        orderNo: 'ORD20230425003',
        createTime: '2023-04-25 09:15:30',
        status: 2,
        totalAmount: 15600,
        payType: 0,
        items: [
          {
            medicineName: '维生素C片',
            price: 26.0,
            quantity: 2,
            image: 'https://via.placeholder.com/60x60?text=维生素C'
          },
          {
            medicineName: '板蓝根颗粒',
            price: 26.0,
            quantity: 4,
            image: 'https://via.placeholder.com/60x60?text=板蓝根'
          }
        ]
      }
    ]
    total.value = 3
  }
}

// 初始化
onMounted(() => {
  getOrderList()
})

// 搜索订单
const handleQuery = () => {
  queryParams.pageNum = 1
  getOrderList()
}

// 重置搜索条件
const resetQuery = () => {
  queryParams.orderNo = ''
  queryParams.status = ''
  handleQuery()
}

// 处理每页数量变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getOrderList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getOrderList()
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '暂无'
  return dateStr
}

// 获取订单状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待付款',
    1: '待发货',
    2: '已发货',
    3: '已完成',
    4: '已取消'
  }
  return statusMap[status] || '未知状态'
}

// 获取订单状态类型（用于标签颜色）
const getStatusType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'primary',
    2: 'success',
    3: 'info',
    4: 'danger'
  }
  return typeMap[status] || ''
}

// 获取支付方式文本
const getPayTypeText = (payType) => {
  const payTypeMap = {
    0: '支付宝',
    1: '微信',
    2: '银行卡'
  }
  return payTypeMap[payType] || '未知方式'
}

// 计算订单商品总数
const getTotalItems = (items) => {
  if (!items || !items.length) return 0
  return items.reduce((total, item) => total + item.quantity, 0)
}

// 查看订单详情
const viewOrderDetail = (orderId) => {
  router.push(`/user/order/detail/${orderId}`)
}

// 取消订单
const cancelOrder = (orderId) => {
  ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        // 调用取消订单API
        await apiCancelOrder(orderId)
        ElMessage.success('订单已取消')
        getOrderList()
      } catch (error) {
        console.error('取消订单失败', error)
        ElMessage.error('取消订单失败，请稍后再试')

        // 模拟取消成功
        setTimeout(() => {
          ElMessage.success('订单已取消')
          // 更新本地订单状态
          const order = orderList.value.find((item) => item.id === orderId)
          if (order) {
            order.status = 4
          }
        }, 500)
      }
    })
    .catch(() => {
      // 取消操作
    })
}

// 去支付
const payOrder = (orderId) => {
  const order = orderList.value.find((item) => item.id === orderId)
  if (!order) {
    ElMessage.error('订单信息不存在')
    return
  }

  currentOrder.value = order
  payDialogVisible.value = true
}

// 确认支付
const confirmPayment = () => {
  ElMessage.success('支付成功')
  payDialogVisible.value = false

  // 更新本地订单状态
  const order = orderList.value.find((item) => item.id === currentOrder.value.id)
  if (order) {
    order.status = 1
  }
}

// 确认收货
const confirmReceive = (orderId) => {
  ElMessageBox.confirm('确认已收到商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  })
    .then(async () => {
      try {
        // 调用确认收货API
        await apiConfirmReceive(orderId)
        ElMessage.success('已确认收货')
        getOrderList()
      } catch (error) {
        console.error('确认收货失败', error)
        ElMessage.error('确认收货失败，请稍后再试')

        // 模拟确认收货成功
        setTimeout(() => {
          ElMessage.success('已确认收货')
          // 更新本地订单状态
          const order = orderList.value.find((item) => item.id === orderId)
          if (order) {
            order.status = 3
          }
        }, 500)
      }
    })
    .catch(() => {
      // 取消操作
    })
}

// 前往药品列表
const goToMedicineList = () => {
  router.push('/user/medicine')
}
</script>

<style scoped>
.order-container {
  padding: 20px 0;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}

.order-header h2 {
  margin: 0;
}

.order-search {
  margin-top: 10px;
}

.order-item {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.order-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

.order-item-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.order-no {
  font-weight: bold;
}

.order-time {
  color: #606266;
}

.order-product-name {
  font-size: 14px;
  margin-bottom: 5px;
}

.order-product-price {
  color: #909399;
  font-size: 12px;
}

.order-product-subtotal {
  color: #f56c6c;
  font-size: 14px;
}

.order-item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background-color: #f5f7fa;
  border-top: 1px solid #ebeef5;
}

.order-total {
  font-size: 14px;
}

.order-total-price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.pay-dialog-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.pay-amount {
  margin-bottom: 20px;
  font-size: 16px;
}

.pay-price {
  color: #f56c6c;
  font-size: 24px;
  font-weight: bold;
}

.pay-qrcode {
  text-align: center;
}

.pay-qrcode p {
  margin-top: 10px;
  color: #606266;
}

@media (max-width: 768px) {
  .order-item-header,
  .order-item-footer {
    flex-direction: column;
    align-items: flex-start;
  }

  .order-item-status,
  .order-actions {
    margin-top: 10px;
  }

  .order-item-info {
    flex-direction: column;
    gap: 5px;
  }
}
</style>
